package com.mincko.minckotest.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.googlecode.objectify.Objectify;
import com.mincko.minckotest.PMF;
import com.mincko.minckotest.shared.Image;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.gson.Gson;
import java.util.Iterator;
/*import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.googlecode.objectify.Objectify;
import com.mincko.minckotest.PMF;
import com.mincko.minckotest.shared.Image;
*/
public class SaveImage extends HttpServlet {
	private Objectify ofy;
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
    	
        String strJson = req.getParameter("jsonData");
        
        if(strJson != null){ //update image if the json is not empty.
    		String strJsonDel = req.getParameter("jsonDelete");
    	    Image data;
        	//do the delete first
        	if(strJsonDel!=null && strJsonDel!=""){
        		data = new Gson().fromJson(strJsonDel, Image.class);
        		if (ofy == null) ofy = PMF.getObjectify();
        		//need to delete blobstoreServic
        		 BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
        		 for (Iterator<Image> iter = data.getImgList().iterator(); iter.hasNext();) {
         			Image img =  ofy.get(Image.class, ((Image) iter.next()).id);
         			BlobKey blobKey = new BlobKey(img.blobKey);
         			//if(blobKey !=null)
         				//blobstoreService.delete(blobKey);
         		}
        		ofy.delete(data.getImgList());
        	}
        	
            data = new Gson().fromJson(strJson, Image.class);
            for (Iterator<Image> iter = data.getImgList().iterator(); iter.hasNext();) {
    			Image img = (Image) iter.next();
    			saveImageData(img.id, null,null, img.description, img.order );
    		}
        }
        else if (req.getParameter("websiteComponentIdentifier") !=null) { //otherwise, add new image
        	saveImageData(0,req.getParameter("websiteComponentIdentifier"), req.getParameter("blobkey"), req.getParameter("description"), 0);
        }

//        // Try-out : writing the code to a second blob in blobstore
//        //
//        FileService fileService = FileServiceFactory.getFileService();
//        AppEngineFile file = fileService.createNewBlobFile("image/jpg");
//        // Open a channel to write to it
//        BlobKey bk= new BlobKey( strBlobKey);
//        
//        BlobInfoFactory bif= new BlobInfoFactory();
//        BlobInfo bi= bif.loadBlobInfo( bk);
//        byte [] data = blobstoreService.fetchData( bk, 0, bi.getSize());
//        
//        FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
//        // This time we write to the channel directly
//        writeChannel.write(ByteBuffer.wrap(data));
//        // Now finalize
//        writeChannel.closeFinally();
//        
//        // Now read from the file using the Blobstore API
//        BlobKey blobKey = fileService.getBlobKey(file);
//        //BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();
//        //String segment = new String(blobStoreService.fetchData(blobKey, 30, 40));
//        System.out.println( blobKey.toString());
      

    }
    /*
     * Desc - to save the data, add/update
    */
    public void saveImageData(long id, String websiteComponentIdentifier, String strBlobKey, String strDescription, Integer intOrder) {
    	
    	if (ofy == null) ofy = PMF.getObjectify();
        Image image;
    	//add new image
    	if(id == 0) {
            // Save in database
    		intOrder = ofy.query(Image.class).filter( "webComponentIdentifier",websiteComponentIdentifier).count()+1;
            image= new Image();
            image.setBlobKey( strBlobKey );
            image.setDescription( strDescription);
            image.setOrder( intOrder);
            image.setWebComponentIdentifier(websiteComponentIdentifier);
            
            
    	}else{ //updating the image
    		image=  ofy.get(Image.class, id);
            if(strBlobKey !=null) image.setBlobKey( strBlobKey );
            if(strDescription !=null) image.setDescription( strDescription);
            image.setOrder( intOrder);
            if(websiteComponentIdentifier !=null) image.setWebComponentIdentifier(websiteComponentIdentifier);
    	}
    	//save the image
    	ofy.put(image);
    }
}

